<template>
<div class="comment">
  <h3>发表评论</h3>
  <textarea placeholder="请发表评论巴拉巴拉(内容最多120字)" maxlength="120" v-model.trim="textvalue"></textarea>
  <mt-button type="primary" size="large" @click="addComment">发表评论</mt-button>
  <div class="container">
    <div class="container-box" v-for="(item,index) in comments" :key="index">
      <div class="container-title">
        第{{index+1}}楼:&nbsp;&nbsp;{{item.user_name}}&nbsp;&nbsp;发表时间:&nbsp;{{item.add_time | timeFormat}}
      </div>
      <div class="container-body">
        {{item.content}}
      </div>
    </div>
  </div>
  <mt-button type="primary" size="large" plain @click="getMore">加载更多</mt-button>  
</div>
</template>

<script>
import { Toast } from "mint-ui";

export default {
  data() {
    return {
      pageIndex: 1,
      comments: [],
      textvalue: null
    };
  },
  created() {
    this.getComment();
  },
  props: ["id"],

  methods: {
    getComment() {
      this.$http
        .get("api/getcomments/" + this.id + "?pageindex=" + this.pageIndex)
        .then(res => {
          if (res.body.status == 0 && res.body.message.length) {
            console.log(res.body);
            // 数据加载更多时需要拼接
            this.comments = this.comments.concat(res.body.message);
          } else {
            Toast("评论加载失败");
          }
        });
    },
    getMore() {
      this.pageIndex++;
      this.getComment();
    },
    addComment() {
      // post请求需要三个参数
      this.$http
        .post("api/postcomment/" + this.$route.params.id, {
          content: this.textvalue
        })
        .then(res => {
          this.comments.unshift({
            content: this.textvalue,
            user_name: "匿名用户",
            add_time: new Date()
          });
          this.textvalue = null;
        });
    }
  }
};
</script>

<style lang="less" scoped>
.comment {
  h3 {
    font-size: 20px;
    text-align: left;
  }
  textarea {
    height: 100px;
    font-size: 10px;
    margin: 0;
  }
  .container {
    .container-box {
      font-size: 12px;
      .container-title {
        margin: 5px 0;
        background-color: #999;
        color: #fff;
      }
      .container-body {
        padding-left: 10px;
        line-height: 1.5em;
      }
    }
  }
}
</style>